import React, { useCallback, useEffect, useState } from 'react';
import { View } from '@tarojs/components';
import Taro, { usePullDownRefresh, useReachBottom } from '@tarojs/taro'
import PageContainer from '../../components/pageContainer';
import SearchBar from './components/searchBar';
import ItemCard from './components/itemCard';
import events from '../../utils/events';
import request from '../../common/request';
import './index.scss';

const pageSize = 20;
function Index() {
  const [list,setList] = useState([]);
  const [ reachBottom, setReachBottom] = useState(false);// 是否可以触底分页
  // 当前页面
  const [ page, setPage] = useState(1);

  const searchBarOnClick = useCallback(()=>{
    Taro.navigateTo({
      url: `/pages/index/searchPage`,
    });
  },[]);

  const postData = useCallback((pageIndex = 1)=>{
    // const parm = {
    //   condition: {},
    //   pagingQuery: {
    //     pageIndex: pageIndex,
    //     pageSize
    //   },
    // };
    // request({method : 'GET', tartget: 'orderConsignorOrderList', data: parm }).then((data)=>{
    //   if (data.success) {
    //     Taro.stopPullDownRefresh();
    //     if (data.pageInfo.pageIndex*data.pageInfo.pageSize > data.pageInfo.total) {
    //       setReachBottom(false);
    //     } else {
    //       setReachBottom(true);
    //     }
    //     if (pageIndex > 1) {
    //       setPage(pageIndex);
    //       setList(list.concat(data.models || []));
    //     } else {
    //       setPage(pageIndex);
    //       setList(data.models || []);
    //     }
    //   }
    // });
  },[]);

  // 新增编辑完毕后刷新首页列表
  useEffect(()=>{
    events.on('index-page-flush', function () {
      postData();
    })
    // 缓存默认市场
    request({method : 'GET', tartget: 'userInfoQuery', data: {} }).then((data)=>{
      if (data.success && data.model) {
        // 存储默认市场
        Taro.setStorageSync('market', {
          marketName:data.model.marketName,
          marketId:data.model.marketId,
        });
      }
    });
  },[]);

  // 下拉刷新
  usePullDownRefresh(() => {
    postData();
  });

  useReachBottom(()=>{
    if (reachBottom) {
      postData(page + 1);
    }
  });

  useEffect(()=>{
    postData();
  },[]);

  return (
    <View>
      <PageContainer noPadding>
        <View style={{ position:'fixed', top: 0, width: '100%', zIndex: 4 }}>
          <SearchBar onClick={searchBarOnClick} disabled />
        </View>
        <View className='vheight' />
        {
          list.length > 0 ?(
            <>
              {
                list.map((i)=>{
                  return (<ItemCard item={i} key={i.id} />);
                })
              }
            </>
          ): (
          <View style={{ height: '30px', fontSize: '14px', display: 'flex',alignItems: 'center', justifyContent: 'center'}}>暂无数据</View>
          )
        }
      </PageContainer>
    </View>
  );
}

export default Index;
